using System;
using System.Threading.Tasks;
using FytSoa.Domain.Core.Jwt;
using FytSoa.Domain.Core.Jwt.Model;
using FytSoa.Domain.Core.Result;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

namespace FytSoa.CrossCutting.Middleware.Filter
{
    public class JwtTokenFilter {
        private readonly RequestDelegate _next;

        public JwtTokenFilter (RequestDelegate next) {
            _next = next;
        }

        public Task Invoke (HttpContext context) {
            if (context.Request.Method == "OPTIONS") {
                return _next (context);
            }
            var headers = context.Request.Headers;
            //自动刷新token
            var token = headers["accessToken"];
            if (string.IsNullOrEmpty(token)) return _next(context);
            var jwtToken = JwtAuthService.SerializeJwt (token);
            var ts = DateTime.Now.Subtract (jwtToken.Time);
            if (ts.Minutes <= 30) return _next(context);
            var newToken = JwtAuthService.IssueJwt (new JwtToken () { Id = jwtToken.Id, FullName = jwtToken.FullName, Role = "Admin", Time = DateTime.Now });
            context.Response.Headers.Add ("RefreshToken", newToken);

            //if (!headers.ContainsKey("Authorization"))
            //{
            //    string path = context.Request.Path.Value;
            //    if (path.Contains("swagger") || path.Contains("token"))
            //    {
            //        return _next(context);
            //    }
            //    // check authorize  wait...
            //    return JwtTokenHandlerAsync(context);
            //}
            return _next (context);
        }

        private async Task JwtTokenHandlerAsync (HttpContext context) {
            context.Response.ContentType = "application/json";

            var result = JsonConvert.SerializeObject (new ApiResult<string> () {
                Code = 401,
                Message = "无权限"
            });

            await context.Response.WriteAsync (result);
        }
    }
}